<?php

namespace addons\fzdc\library;


use addons\fzdc\library\XinYe\PrintService as PService;
use addons\fzdc\library\XinYe\util\NoteFormatter;
use addons\fzdc\library\feie\HttpClient;
use app\admin\model\fzdc\coupon\Coupon;
use app\admin\model\fzdc\order\Detail;
use app\admin\model\fzdc\order\Order;
use app\admin\model\fzdc\prin\Prin;
use app\admin\model\fzdc\prin\Prinlog;
use app\admin\model\fzdc\store\Sear;
use app\admin\model\fzdc\store\Store;
use app\admin\model\fzdc\user\Address;
use think\Exception;
use think\Log;

class printer
{

    protected static $configs = [];


    /**
     * 打印指定模板 指定设备
     * @param int $id 模板id
     */
    public static function printing($store,$id,$orderId,$flag=0)
    {
        $prin = Prin::get($id);

        //替换打印内容
        $data = Order::get($orderId);
        if ($data['order_type']==1){
            $data['order_type']="自取";
            $address = "";
        }elseif($data['order_type']==2){
            $addressInfo = json_decode($data['address_info'],true);
            $data['order_type']="外卖";



            $address = (isset($addressInfo['address']) ? $addressInfo['address'] : "" . "<BR>" . isset($addressInfo['remark'])) ? $addressInfo['remark'] : "" . "<BR>";
            $address .= (isset($addressInfo['title']) ? $addressInfo['title'] : "" . " " . isset($addressInfo['mobile'])) ? $addressInfo['mobile'] : "";
            
        }else{
            $data['order_type']="堂食";
            $address = "";
        }
        if ($data['pay_type']==1){
            $data['pay_type']="支付方式：微信支付";
        }elseif ($data['pay_type']==2){
            $data['pay_type']="支付方式：钱包支付";
        }elseif ($data['pay_type']==3){
            $data['pay_type']="支付方式：现金支付";
        }else{
            $data['pay_type']="支付方式：暂无";
        }


        if ($flag==1){
            $tag = false;
            $group = Detail::where(['order_id' => $orderId])->group("numbers")->column("numbers");
        }else{
            $group = Detail::where(['order_id' => $orderId,'print_status' => 0])->group("numbers")->column("numbers");

            $tag = Detail::where(['print_status' => 1,"order_id"=>$orderId])->count();
        }

        $couponInfo = Coupon::where("id",$data['coupon_id'])->find();
        if (empty($couponInfo)) {
            $preferential = 0 ;
        }else{
            $preferential = $couponInfo['used_amount'];

        }
        $html = '';
        $orderTotalmoney = 0;
        if ($prin->brand=="xinyeyun"){
            $qz = '<L>';
        }else{
            $qz = '';
        }
        foreach ($group as $grow) {
            if ($flag==1){
                $list = Detail::with(['store','goods'])
                    ->where(['detail.order_id' => $orderId])
                    ->where(['detail.numbers' => $grow])
                    ->select();
            }else{
                $list = Detail::with(['store','goods'])
                    ->where(['detail.order_id' => $orderId])
                    ->where(['detail.print_status' => 0,'detail.numbers' => $grow])
                    ->select();
            }

            foreach ($list as $key => $row) {
                if ($key == 0){
                    if ($row['numbers'] == 1){
                        $html .=  "**************商品**************".'<BR>';
                    }else{
                        $html .=  "************第".($row['numbers']-1)."次加菜***********".'<BR>';
                    }
                }
                $html .=  $qz.NoteFormatter::formatPrintOrderItem($row['goods_name'] ,"x".$row['goods_count'] ,$row['goods_price'].'元');
                if ($row['item_name']){
                    $html .= $qz.'规格:'.$row['item_name'].'<BR>';
                }
                $html .= $qz;
                $orderTotalmoney = $orderTotalmoney + $row['goods_price']*$row['goods_count'];
            }

        }

        if ($data['seat_id']){
            $seat_title = Sear::whereIn("id",explode(",",$data['seat_id']))->column("title");
            $seat_title = implode(",",$seat_title);
            $tmp = str_replace("#seatname#",$seat_title ,$prin->print_temp);
        }else{
            $tmp = str_replace("#seatname#","无",$prin->print_temp);
        }

        $tmp = str_replace("#storename#",$store['title'] ,$tmp);
        $tmp = str_replace("#ordertype#",$data['order_type'] ,$tmp);
        $tmp = str_replace("#paytype#",$data['pay_type'] ,$tmp);
        $tmp = str_replace("#storename#",$store['title'] ,$tmp);
        $tmp = str_replace("#orderTime#",date("Y年m月d日 H时i分",$data['createtime']) ,$tmp);
        $tmp = str_replace("#orderid#",$data['order_no'] ,$tmp);
        $tmp = str_replace("#shoplist#",$html ,$tmp);

        $tmp = str_replace("#total#",$orderTotalmoney ,$tmp);
        $tmp = str_replace("#qucancode#",$data['code'] ,$tmp);
        if ($tag){
            $tmp = str_replace("#totalmoney#",$orderTotalmoney ,$tmp);
        }else{
            $tmp = str_replace("#totalmoney#",$data['order_amount_total'] ,$tmp);
        }
        if ($data['code']){
            $tmp = str_replace("#code#","取餐码：".$data['code'] ,$tmp);
        }else{
            $tmp = str_replace("#code#","" ,$tmp);
        }
        $tmp = str_replace("#preferential#",$preferential ,$tmp);
        if (empty($address)){
            $tmp = str_replace("#address#",$address ,$tmp);
        }else{
            $tmp = str_replace("#address#","配送地址:".$address ,$tmp);
        }
        if ($data['subscribe_tel']){
            $tmp = str_replace("#subscribe_tel#","预留电话：".$data['subscribe_tel'] ,$tmp);
        }else{
            $tmp = str_replace("#subscribe_tel#","" ,$tmp);
        }
        $tmp = str_replace("#notes#",empty($data['remark'])?"无备注":$data['remark'] ,$tmp);
        $prin->print_temp = $tmp;

        switch ($prin->brand) {
            case 'feie':
                self::feie($prin,$orderId);
                break;
            case 'xinyeyun':
                self::xinyeyun($prin,$orderId);
                break;
        }

    }

    public static function test()
    {
        /**
         * 参考例子 1
         * [循环调用接口，实现多台打印机同时出单打印] 例如前台打印机和后厨打印机同时出单
         */
        $content = '<CB>测试打印</CB><BR>';
        $content .= '名称　　　　　 单价  数量 金额<BR>';
        $content .= '--------------------------------<BR>';
        $content .= '饭　　　　　 　10.0   10  100.0<BR>';
        $content .= '炒饭　　　　　 10.0   10  100.0<BR>';
        $content .= '蛋炒饭　　　　 10.0   10  100.0<BR>';
        $content .= '鸡蛋炒饭　　　 10.0   10  100.0<BR>';
        $content .= '西红柿炒饭　　 10.0   10  100.0<BR>';
        $content .= '西红柿蛋炒饭　 10.0   10  100.0<BR>';
        $content .= '西红柿鸡蛋炒饭 10.0   10  100.0<BR>';
        $content .= '--------------------------------<BR>';
        $content .= '备注：加辣<BR>';
        $content .= '合计：xx.0元<BR>';
        $content .= '送货地点：广州市南沙区xx路xx号<BR>';
        $content .= '联系电话：13888888888888<BR>';
        $content .= '订餐时间：2014-08-08 08:08:08<BR>';
        $content .= '<QR>http://www.feieyun.com</QR>';//把二维码字符串用标签套上即可自动生成二维码

        $printer = Prin::get(1); //假设打印机ID为1
        $printer->print_temp = $content; //替换模板内容
        self::feie($printer,1);//调用云打印接口
    }


    public static function feie($printer,$orderId)
    {
        $time = time();         //请求时间
        $msgInfo = array(
            'user' => $printer->print_name,
            'stime' => $time,
            'sig' => sha1($printer->print_name . $printer->print_key . $time),
            'apiname' => $printer->print_msg,
            'sn' => $printer->sn,
            'content' => $printer->print_temp,
            'times' => $printer->count //打印次数
        );

        $client = new HttpClient($printer->ip, $printer->port);
        if (!$client->post($printer->path, $msgInfo)) {
            throw new Exception('飞鹅云打印机sn：' . $printer->sn . '打印失败');
        } else {
            //服务器返回的JSON字符串，建议要当做日志记录起来
            $result = $client->getContent();
            $result = json_decode($result,true);
            if($result['ret']==0){
                Order::where("id",$orderId)->update(['print_no'=>$result['data']]);
                //添加打印日志
                self::print_log($orderId);
                return true;
            }else{
                throw new Exception('飞鹅云打印机error：' . $result['msg']);
            }
        }
    }


    public static function xinyeyun($prin,$orderId){

        $data = Order::get($orderId);
        $PService = new PService();
        $pdata['sn'] = $prin->sn;
        //第一步检查打印的状态
        $printSt = $PService->xpYunQueryPrinterStatus($pdata);
        if ($printSt['code'] !=0) {
            throw new Exception($printSt['msg']);
        }

        //*必填*：打印内容,不能超过12K
        $pdata['content'] = $prin->print_temp;
        $pdata['copies'] = 1;
        $pdata['payType'] = 41;
        $pdata['voice'] = 2;
        $pdata['mode'] = 1;
        $pdata['payMode'] = 61;
        $pdata['money'] = $data['order_amount_total'];
        //仅用于支持金额播报的芯烨云打印机。
        $result = $PService->xpYunPrint($pdata);
        if($result['code']==0){
            Order::where("id",$orderId)->update(['print_no'=>$result['data']]);
            //添加打印日志
            self::print_log($orderId);
            return true;
        }else{
            throw new Exception($result['msg']);
        }
    }

    public static function print_log($orderId){
        $order_info = Order::get($orderId);
        if ($order_info){
            $store_info = Store::get($order_info['store_id']);
        }
        Detail::where(["order_id"=>$orderId])->update(['print_status' => 1]);
        Prinlog::create([
            'order_no' => isset($order_info['order_no'])? $order_info['order_no'] : '',
            'store_name' => isset($store_info['title'])? $store_info['title']:'',
            'createtime' => time(),
            'updatetime' => time(),
        ]);
    }
}
